<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\wh\model\Material as MaterialModel;
use app\wh\model\Supplier as SupplierModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\MaterialGoods as MaterialGoodsModel;
use app\wh\model\Stock as StockModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\wh\model\Color as ColorModel;
use think\Db;
use think\facade\Env;

/**
 * 库存控制器
 * @package app\admin\controller
 */
class Stock extends Admin
{
    public $_type_pid = '';
    public $_type_id = '';
    /**
     * 初始化
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     */
    protected function initialize(){
        parent::initialize();

        $this->_type_pid = input('stock_ptype',cookie('_type_pid'));

        $this->_type_id = input('stock_type',cookie('_type_id'));
        cookie('_type_id',$this->_type_id);

        if(input('stock_ptype') && !input('stock_type')){
            $this->_type_id = '';
            cookie('_type_id',null);
        }

        if($this->_type_id)$this->_type_pid = Db::name('wh_stock_type')->where(['id'=>$this->_type_id])->value('pid');
        elseif(empty($this->_type_pid))$this->_type_pid = StockTypeModel::getTypePidFirst(0,false);
        cookie('_type_pid',$this->_type_pid);

    }
    //首页
    public function index(){

        return $this->fetch();
    }

    /**
     * 新增库存
     */
    public function add(){

        $id = input('id');
        $type_pid = input('type_pid');
        $type_id = input('type_id');
        $info = [];

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($id)$info = Db::name('wh_stock')->where(['id'=>$id])->find();
            // 验证
            if(empty($data['title']))$this->error('请填写库存名称');
            if(empty($data['supplier_id']))$this->error('请选择供应商');
            if(empty($data['type_pid']))$this->error('请选择物料类别');
            if(empty($data['type_id']))$this->error('请选择类别');
            if(in_array($data['type_pid'],ColorModel::$type_pid_arr)){
                if(empty($data['supplier_color']))$this->error('请填写厂家色号');
                if(empty($data['color_type_id']))$this->error('请填写油漆类型');

                $data['supplier_color'] = strtoupper(trim($data['supplier_color']));
                $data['model'] = $data['supplier_color'];
                //生成自编码
                if(empty($data['color_sn']))$data['color_sn'] = ColorModel::getColorSn($data['type_id'],$data['heat']);
                elseif (!empty($id)){
                    //如果更换了物料类型，则自编码也根据物料类型进行更新
                    if($info['type_id'] != $data['type_id'])$data['color_sn'] = ColorModel::getColorSn($data['type_id'],$data['heat']);
                }
            }
            elseif (in_array($data['type_pid'],[5])){
                if(empty($data['model']))$this->error('请填写规格型号');
                if(empty($data['long']))$this->error('请填写长');
                if(empty($data['high']))$this->error('请填写高');
            }
            elseif (in_array($data['type_pid'],[4])){
                if(empty($data['thickness']))$this->error('请填写厚度');
                if(empty($data['model']))$this->error('请填写规格型号');
                if(empty($data['quality']))$this->error('请选择材质');
                if(empty($data['lot_sn']))$this->error('请填写批号');
                $data['model2'] = $data['lot_sn'];
                $data['high'] = $data['model'];
            }
            else{
                if(empty($data['model']))$this->error('请填写规格型号');
            }

            //判断是否已录入
            $in_sn = StockModel::getStockSn($data,false);
            unset($data['edit_stock_id']);

            if(!empty($in_sn)){
                if($id){
                    if($info['stock_sn'] != $in_sn)$this->error('该物料已录入库存');
                }
                else $this->error('该物料已录入库存');

            }

            if(empty($data['model']))$data['model'] = $data['supplier_color'];
            if(empty($data['id'])){

                $re = StockModel::getStockSn($data);
                Db::name('wh_stock')->where(['stock_sn'=>$re])->update(['number'=>$data['number']]);
            }
            else $re = Db::name('wh_stock')->where(['id'=>$data['id']])->update($data);

            //更新厂家色号
            $stock_sn = StockModel::getStockSn($data);
            $color_add = [
                'supplier_id'       =>  $data['supplier_id'],
                'type_pid'          =>  $data['type_pid'],
                'type_id'           =>  $data['type_id'],
                'type_id2'          =>  isset($data['type_id2'])?$data['type_id2']:'',
                'type_id3'          =>  isset($data['type_id3'])?$data['type_id3']:'',
                'supplier_color'    =>  $data['model'],
                'heat'              =>  $data['heat'],
                'color_type_id'     =>  $data['color_type_id'],
                'color'             =>  $data['title'],
            ];
            Db::name('wh_order_color')->where(['stock_sn'=>$stock_sn])->update($color_add);

            //同步新增同规格不同物料类别的库存
            StockModel::addSameStock($stock_sn,$info);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');

            $this->error('操作失败');
        }

        $info = Db::name('wh_stock')->where(['id'=>$id])->find();
        if(empty($info['type_pid']))$info['type_pid'] = $type_pid;
        if(empty($info['type_id']))$info['type_id'] = $type_id;
        //$info['type_title'] = Db::name('wh_stock_type')->where(['id'=>$info['type_id']])->value('title');

        $supplier = SupplierModel::getGroup(0,$info['type_pid']);
        $type_plist = StockTypeModel::getGroup();
        $type_list = StockTypeModel::getGroup($info['type_pid']);
        $type_list2 = [];
        if(!empty($info['type_id']))$type_list2 = StockTypeModel::getGroup($info['type_id']);
        $type_list3 = [];
        if(!empty($info['type_id2']))$type_list3 = StockTypeModel::getGroup($info['type_id2']);
        return ZBuilder::make('form')
            ->setPageTitle('新增库存') // 页面标题
            ->addHidden('id')
            ->addHidden('color_id')
            ->addHidden('color_sn')
            ->addFormItems([ // 批量添加表单项
                ['linkage:12||||must', 'type_pid', '物料类别', '', $type_plist,'', url('getStockType'), 'type_id'],
                ['linkage:12||||must', 'type_id', '类别', '', $type_list,'', url('getStockType'), 'type_id2'],
                //['linkage:12||||must', 'type_id2', '类别2', '', $type_list2,'', url('getStockType'), 'type_id3'],
                //['select:12||||must', 'type_id3', '类别3', '', $type_list3],
                ['text:12||||must', 'title', '库存名称'],
                ['select:12||||must', 'supplier_id', '供应商', '', $supplier,''],
                ['text:12||||must', 'supplier_color', '厂家色号'],
                ['select:12||||must', 'heat', '油温', '', MaterialModel::$heat,''],
                ['select:12||||must', 'color_type_id', '油漆类型', '', ColorModel::getColorType(),''],
                ['text:12||||must', 'model', '规格型号'],
                ['select:12||||must', 'quality', '材质', '', ColorModel::getQuality($info['type_pid'])],
                ['text:12||||must', 'lot_sn', '批号'],
                ['text:12||||must', 'thickness', '厚度'],
                ['text:12||||must', 'long', '长'],
                ['text:12||||must', 'high', '宽'],
                ['number:12||||must', 'number', '库存'],
                ['number:12||||must', 'num', '重量'],
                ['image:12||||must', 'img', '色卡'],
            ])
            ->setTrigger('type_pid',implode(',',ColorModel::$type_pid_arr),'supplier_color,color_sn,heat,color_type_id,type_id2,type_id3,img')
            ->setTrigger('type_pid','5','model,long,high,num')
            ->setTrigger('type_pid','3,6,7','model',false)
            ->setTrigger('type_pid','4','model,thickness,lot_sn,quality',false)
            ->setTrigger('type_pid','31,32','model',false)
            ->setFormData($info)
            ->layout(['type_ptitle'=>12])
            ->fetch();
    }

    /**
     * 库存详情列表页
     */
    public function inventory()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = $this->_type_id;
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('inventory');

        $supplier_list = SupplierModel::getGroup(0,$type_pid);
        $type_list2 = StockTypeModel::getGroup($stock_type);
        $type_list3 = [];
        if(!empty($type_list2))$type_list3 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',$type_list2)]]);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
            elseif(!empty($mv[0]) && $mv[0] == 'is_number' && !empty($mv[2])){
                $is_number = $mv[2];
                //无库存
                if($is_number == 1){
                    $map2 .= " and s.number = 0";
                }
                //有库存
                if($is_number == 2){
                    $map2 .= " and s.number > 0";
                }
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);

        if($stock_type)$map[] = ['s.type_id','=',$stock_type];
        else $map[] = ['s.type_pid','=',$type_pid];

        // 数据列表
        $data_list = Db::name('wh_stock')
            ->alias('s')
            ->field('s.*,s.stock_sn as stock_sn_img,t.title as type_pname,tt.title as type_name,ss.title_abb as supplier_name')
            ->leftJoin('wh_stock_type t','t.id=s.type_pid')
            ->leftJoin('wh_stock_type tt','tt.id=s.type_id')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->where($map)
            ->where($map2)
            ->group('s.stock_sn')
            ->order('s.model asc,s.type_id asc,s.supplier_id asc,s.stock_sn desc')
            ->paginate()
            ->each(function ($v){
                $v['loss'] = StockModel::getLossNumber($v);
                //最后一次盘存时间
                $v['loss_time'] = Db::name('wh_stock_take_log')->where(['stock_sn'=>$v['stock_sn']])->order('create_time desc')->value('create_time');
                if(!empty($v['loss_time']))$v['loss'] .= "<a class=\"text-danger\">[".date('Y-m-d',$v['loss_time'])."]</a>";

                //最后一次入库时间
                $v['log_time'] = Db::name('wh_stock_log')->where(['stock_sn'=>$v['stock_sn'],'status'=>0])->order('create_time desc')->value('create_time');

                //获取总库存
                $v['sum_number'] = StockModel::getSumNumber($v);

                //$where['supplier_id'] = $v['supplier_id'];
                $where['type_pid'] = $v['type_pid'];
                $where['type_id'] = $v['type_id'];
                $where['type_id2'] = $v['type_id2'];
                $where['model'] = $v['model'];

                $v['sum_number'] = Db::name('wh_stock')->where($where)->sum('number');

                //油漆类，显示三级分类
                if(in_array($v['type_pid'],ColorModel::$type_pid_arr) && !empty($v['type_id2'])){
                    $v['type_name'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value(['title']);
                }
                //四级分类
                $v['type_name3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value(['title']);

                return $v;
            })
        ;

        $stockStat = StockModel::getOneStat($stock_type,'type_id');

        $top_arr = [
            [
                'left'  =>  ['title'=>'总的库存数量','value'=>$stockStat['number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'入库数量','value'=>$stockStat['join_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'出库数量','value'=>$stockStat['out_number'],'angle'=>'kg']
            ],
        ];

        $top_html = StockModel::topStatHtml($top_arr);

        //列表表头
        $tab_column = [
            // 批量添加列
            'type_name'             =>  ['type_name', '物料类别'],
            'type_name3'            =>  ['type_name3', '类别'],
            'model'                 =>  ['model', '型号规格'],
            'supplier_name'         =>  ['supplier_name', '供应商'],
            'title'                 =>  ['title', '物料名称'],
            'supplier_color'        =>  ['supplier_color', '厂家色号'],
            'color_sn'              =>  ['color_sn', '自编号'],
            'heat'                  =>  ['heat', '油温',MaterialModel::$heat],
            'color_type_id'         =>  ['color_type_id', '油漆类型',ColorModel::getColorType()],
            'img'                   =>  ['img','色卡','picture'],
            'number'                =>  ['number', '库存'],
            'num'                   =>  ['num', '数量'],
            'loss'                  =>  ['loss', '损耗'],
            'log_time'              =>  ['log_time', '入库时间','date'],
            'note'                  =>  ['note', '备注','text.edit'],
            ['stock_sn_img','条形码','callback',function($value, $data){
                $value = '<div class="js-gallery hidden-xs"> <img style="height: 35px;" class="image barcode" data-val="'.$value.'" data-original="" src=""></div>';
                return $value;
            },'__data__'],
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        //搜索头
        $search_area = [
            ['select:1', 'is_number', '有无库存', 'eq','',[1=>'无库存',2=>'有库存']],
            ['text:1', 's.stock_sn', '条形码', 'like'],
            ['select:2', 's.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:2', 's.model', '型号规格', 'like'],
        ];

        //JS
        $js = '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
            <script type="text/javascript">
                $(function() {
                    //条形码
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{displayValue:true});
                    });
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "库存详情",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['model']);
                unset($tab_column['num']);
                if(empty($type_list3))unset($tab_column['type_name3']);
                $tab_column['title'] = ['title', '颜色名称'];
                unset($search_area[2]);
                $search_area[] = ['text:2', 's.title', '颜色名称', 'like'];
                $search_area[] = ['text:2', 's.supplier_color', '厂家色号', 'like'];
                $search_area[] = ['text:1', 's.color_sn', '自编号', 'like'];
                $search_area[] = ['select:1', 'is_number', '有无库存', 'eq','',[1=>'无库存',2=>'有库存']];
                if(!empty($type_list2)){
                    $search_area2[] = ['select:1', 's.type_id2', '物料类别', 'eq','',$type_list2];
                    $search_area = array_merge($search_area2,$search_area);
                }
                //无油温
                if(in_array($type_pid,ColorModel::$type_pid_not_heat_arr))unset($tab_column['heat']);
                break;
                //铝卷
            case 4:

                unset($tab_column['img']);
                unset($tab_column['num']);
                unset($tab_column['type_name3']);
                $search_area[] = ['text:2', 's.thickness', '厚度', 'like'];
                $search_area[] = ['text:2', 's.lot_sn', '卷号', 'like'];

                $tab_column = [
                    // 批量添加列
                    'type_name'             =>  ['type_name', '系列(类别)'],
                    'type_pname'            =>  ['type_pname', '名称'],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'thickness'             =>  ['thickness', '厚度'],
                    'model'                 =>  ['model', '型号规格'],
                    'quality'               =>  ['quality', '材质',ColorModel::getQuality()],
                    'title'                 =>  ['title', '名称'],
                    'lot_sn'                =>  ['lot_sn', '卷号'],
                    //'num'                   =>  ['num', '数量'],
                    'number'                =>  ['number', '库存(米)'],
                    //'sum_number'            =>  ['sum_number', '总库存(米)'],
                    ['stock_sn_img','条形码','callback',function($value, $data){
                        $value = '<div class="js-gallery hidden-xs"> <img style="height: 35px;" class="image barcode" data-val="'.$value.'" data-original="" src=""></div>';
                        return $value;
                    },'__data__'],
                    'right_button'          =>  ['right_button', '操作', 'btn']
                ];

                break;
            //原材料
            case 3:
            //铝板
            case 5:
                unset($tab_column['img']);
                //unset($tab_column['num']);
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_name']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_type_id']);
                unset($tab_column['color_sn']);
                unset($tab_column['heat']);

            $tab_column['number'] = ['number', '库存(件)'];
            $tab_column['loss'] = ['loss', '损耗(件)'];
            $tab_column['num'] = ['num', '重量'];
                break;
            //化工
            case 6:
                //其他
            default:
                unset($tab_column['img']);
                unset($tab_column['num']);
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_type_id']);
                unset($tab_column['color_sn']);
                unset($tab_column['heat']);
                break;

        }

        //JS
        $js .= '
        <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
        <script type="text/javascript">
            $(function(){
                $(".barcode").each(function(i){
                    var val = $(this).data("val");
                    //$(this).JsBarcode(val,{displayValue:false});
                    $(this).JsBarcode(val,{displayValue:true});
                });
            })
        </script>
        ';

        $sum_number = Db::name('wh_stock')
            ->alias('s')
            ->where($map)
            ->where($map2)
            ->sum('s.number');
        $total_str = "总库存：{$sum_number}&nbsp;&nbsp;&nbsp;&nbsp;";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('库存详情（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            //->hideCheckbox()
            ->setPageTips($total_str,'info','topbtn')
            ->setExtraHtml($top_html,'block_top')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addTopButton('add',['title' => '新增','href' => url('add',['type_pid'=>$type_pid,'type_id'=>$stock_type]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['800px', '80%'], 'title' => ['新增库存', 'font-size:24px;text-align: center;']])
            ->addTopButton('archivesPrint',['title' => '批量打印','href' => url('codePrint'),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addTopButton('editMoreStock',['title' => '批量修改','href' => url('editMoreStock'),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['批量修改', 'font-size:24px;text-align: center;']])
            ->addTopButton('delete',['title' => '删除','href' => url('stockDelete'),'icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('edit',['title' => '修改','href' => url('add',['id' => '__id__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['800px', '80%'], 'title' => ['库存修改', 'font-size:24px;text-align: center;']])
            ->addRightButton('print',['title' => '打印','href' => url('codePrint',['stock_sn' => '__stock_sn__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('addJoin',['title' => '入库','href' => url('addJoin',['stock_sn'=>'__stock_sn__']),'class'=>'btn btn-primary disable-dch','icon'=>''],['area' => ['900px', '70%'], 'title' => ['添加入库记录', 'font-size:24px;text-align: center;']])
            ->addRightButton('addOut',['title' => '出库','href' => url('addOut',['stock_sn'=>'__stock_sn__']),'class'=>'btn btn-primary disable-dch','icon'=>''],['area' => ['900px', '70%'], 'title' => ['添加出库记录', 'font-size:24px;text-align: center;']])
            ->addRightButton('addTake',['title' => '盘存','href' => url('addTake',['stock_sn'=>'__stock_sn__']),'class'=>'btn btn-primary disable-dch','icon'=>''],['area' => ['900px', '70%'], 'title' => ['添加盘存记录', 'font-size:24px;text-align: center;']])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'            => 60,
                'stock_sn_img'  => 55,
                'type_name'     => 55,
                'type_name3'    => 55,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 入库列表页
     */
    public function joinList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = input('stock_type',$this->_type_id);
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('joinlist');

        $supplier_list = SupplierModel::getGroup(0,$type_pid);
        $type_list2 = StockTypeModel::getGroup($stock_type);
        $type_list3 = [];
        if(!empty($type_list2))$type_list3 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',$type_list2)]]);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        if($stock_type)$map[] = ['l.type_id','=',$stock_type];
        else $map[] = ['l.type_pid','=',$type_pid];
        $map[] = ['l.status','=',0];
        //$map[] = ['l.material_sn','=',''];
        $map[] = ['l.cate','=',0];
        // 数据列表
        $data_list = Db::name('wh_stock_log')
            ->alias('l')
            ->field('l.*,s.title,s.color_sn,s.model as supplier_color,s.stock_sn as stock_sn_img,u.nickname,t.title as type_name,ss.title as supplier_name')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=s.type_id')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->leftJoin('admin_user u','u.id=l.uid')
            ->where($map)
            ->where($map2)
            ->group('l.id')
            ->order('l.create_time desc')
            ->paginate()
            ->each(function ($v){

                //油漆类，显示三级分类
                if(in_array($v['type_pid'],ColorModel::$type_pid_arr) && !empty($v['type_id2'])){
                    $v['type_name'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value(['title']);
                }
                //四级分类
                $v['type_name3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value(['title']);

                return $v;
            })
        ;

        $stockStat = StockModel::getOneStat($stock_type,'type_id');

        $top_arr = [
            [
                'left'  =>  ['title'=>'总的库存数量','value'=>$stockStat['number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'入库数量','value'=>$stockStat['join_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'出库数量','value'=>$stockStat['out_number'],'angle'=>'kg']
            ],
        ];

        $top_html = StockModel::topStatHtml($top_arr);

        //列表表头
        $tab_column = [
            // 批量添加列
            'create_time'           =>  ['create_time', '入库时间','datetime'],
            'type_name'             =>  ['type_name', '物料类别'],
            'type_name3'            =>  ['type_name3', '类别'],
            'model'                 =>  ['model', '型号规格'],
            'supplier_name'         =>  ['supplier_name', '供应商'],
            'title'                 =>  ['title', '物料名称'],
            'supplier_color'        =>  ['supplier_color', '厂家色号'],
            'color_sn'              =>  ['color_sn', '自编号'],
            'number'                =>  ['number', '入库数量'],
            'num'                   =>  ['num', '入库数量'],
            'nickname'              =>  ['nickname', '库管'],
            'material_sn'           =>  ['material_sn', '采购单号'],
            ['stock_sn_img','条形码','callback',function($value, $data){
                $value = '<div class="js-gallery"> <img style="height: 35px;" class="image barcode" data-val="'.$value.'" data-original="" src=""></div>';
                return $value;
            },'__data__'],
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        //搜索头
        $search_area = [
            ['select:2', 's.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:2', 's.model', '型号规格', 'like'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['model']);
                if(empty($type_list3))unset($tab_column['type_name3']);
                $tab_column['title'] = ['title', '颜色名称'];
                unset($search_area[1]);
                $search_area[] = ['text:2', 's.supplier_color', '厂家色号', 'like'];
                $search_area[] = ['text:2', 's.color_sn', '自编号', 'like'];
                //无油温
                if(in_array($type_pid,ColorModel::$type_pid_not_heat_arr))unset($tab_column['heat']);
                break;
            //铝卷
            case 4:
                unset($tab_column['num']);
                unset($tab_column['type_name3']);
                $tab_column['supplier_color'] = ['quality', '材质',ColorModel::getQuality()];
                $tab_column['color_sn'] = ['lot_sn', '色号'];

                $search_area[] = ['text:2', 's.lot_sn', '批号', 'like'];
                break;
            //铝板
            case 5:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_name']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);

                $tab_column['num'] = ['num', '入库重量'];
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                unset($tab_column['num']);
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);
                break;
        }
        $search_area[] = ['daterange:2', 'l.create_time', '日期'];


        //JS
        $js = '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
            <script type="text/javascript">
                $(function() {
                    //条形码
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{displayValue:true});
                    });
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "入库记录",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $sum_number = Db::name('wh_stock_log')
            ->alias('l')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->where($map)
            ->where($map2)
            ->sum('l.number');
        $total_str = "入库数量：{$sum_number}&nbsp;&nbsp;&nbsp;&nbsp;";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('入库记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            //->hideCheckbox()
            ->setPageTips($total_str,'info','topbtn')
            ->setExtraHtml($top_html,'block_top')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addTopButton('archivesPrint',['title' => '批量打印','href' => url('codePrint'),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addTopButton('delete',['title' => '删除','href' => url('stockDelete',['type'=>'log']),'icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('print',['title' => '打印','href' => url('codePrint',['stock_sn' => '__stock_sn__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'stock_sn_img'  => 55,
                'type_name'     => 55,
                'type_name3'    => 55,
                'create_time'  => 110,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 出库列表页
     */
    public function outList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = input('stock_type',$this->_type_id);
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('outlist');

        $supplier_list = SupplierModel::getGroup(0,$type_pid);
        $type_list2 = StockTypeModel::getGroup($stock_type);
        $type_list3 = [];
        if(!empty($type_list2))$type_list3 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',$type_list2)]]);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        if($stock_type)$map[] = ['l.type_id','=',$stock_type];
        else $map[] = ['l.type_pid','=',$type_pid];
        $map[] = ['l.status','=',1];
        // 数据列表
        $data_list = Db::name('wh_stock_log')
            ->alias('l')
            ->field('l.*,s.title,s.number as stock_sum_number,s.color_sn,s.supplier_color,s.stock_sn as stock_sn_img,u.nickname,o.engineering,t.title as type_name,ss.title as supplier_name')
            ->leftJoin('mill_order o','o.id=l.order_id')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=s.type_id')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->leftJoin('admin_user u','u.id=l.uid')
            ->where($map)
            ->where($map2)
            ->group('l.id')
            ->order('l.create_time desc')
            ->paginate()
            ->each(function ($v){

                if(empty($v['engineering']) && empty($v['archives_sn']))$v['engineering'] = $v['note'];
                elseif(empty($v['engineering']))$v['engineering'] = $v['archives_sn'];
                else $v['engineering'] .= "({$v['archives_sn']})";

                $v['actual_number'] = $v['number']-$v['back_number'];

                //油漆类，显示三级分类
                if(in_array($v['type_pid'],ColorModel::$type_pid_arr) && !empty($v['type_id2'])){
                    $v['type_name'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value(['title']);
                }
                //四级分类
                $v['type_name3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value(['title']);

                return $v;
            });

        $stockStat = StockModel::getOneStat($stock_type,'type_id');

        $top_arr = [
            [
                'left'  =>  ['title'=>'总的库存数量','value'=>$stockStat['number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'入库数量','value'=>$stockStat['join_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'出库数量','value'=>$stockStat['out_number'],'angle'=>'kg']
            ],
        ];

        $top_html = StockModel::topStatHtml($top_arr);

        //列表表头
        $tab_column = [
            // 批量添加列
            'type_name'             =>  ['type_name', '物料类别'],
            'type_name3'            =>  ['type_name3', '类别'],
            'model'                 =>  ['model', '型号规格'],
            'supplier_name'         =>  ['supplier_name', '供应商'],
            'title'                 =>  ['title', '物料名称'],
            'supplier_color'        =>  ['supplier_color', '厂家色号'],
            'color_sn'              =>  ['color_sn', '自编号'],
            'nickname'              =>  ['nickname', '库管'],
            'number'                =>  ['number', '出库数量'],
            'num'                   =>  ['num', '出库数量'],
            'back_number'           =>  ['back_number', '退还数量'],
            'actual_number'         =>  ['actual_number', '实际出库量'],
            'stock_sum_number'      =>  ['stock_sum_number', '库存量'],
            'create_time'           =>  ['create_time', '日期','datetime'],
            'engineering'           =>  ['engineering', '使用工程'],
            //'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        //搜索头
        $search_area = [
            ['select:2', 's.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:2', 's.model', '型号规格', 'like'],
            ['text:2', 'l.archives_sn', '档案号', 'like'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['model']);
                unset($tab_column['num']);
                if(empty($type_list3))unset($tab_column['type_name3']);
                $tab_column['title'] = ['title', '颜色名称'];
                unset($search_area[1]);
                $search_area[] = ['text:2', 's.supplier_color', '厂家色号', 'like'];
                $search_area[] = ['text:1', 's.color_sn', '自编号', 'like'];
                if(!empty($type_list2)){
                    $search_area2[] = ['select:1', 's.type_id2', '物料类别', 'eq','',$type_list2];
                    $search_area = array_merge($search_area2,$search_area);
                }
                //无油温
                if(in_array($type_pid,ColorModel::$type_pid_not_heat_arr))unset($tab_column['heat']);
                break;
            //铝卷
            case 4:
                unset($tab_column['num']);
                unset($tab_column['type_name3']);
                unset($tab_column['back_number']);
                unset($tab_column['actual_number']);
                $tab_column['supplier_color'] = ['quality', '材质',ColorModel::getQuality()];
                $tab_column['color_sn'] = ['lot_sn', '色号'];

                $search_area[] = ['text:2', 's.lot_sn', '色号', 'like'];
                break;
            //铝板
            case 5:
                unset($tab_column['type_name3']);
                unset($tab_column['back_number']);
                unset($tab_column['actual_number']);
                unset($tab_column['supplier_name']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);

                $tab_column['num'] = ['num', '出库重量'];
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                unset($tab_column['num']);
                unset($tab_column['type_name3']);
                unset($tab_column['back_number']);
                unset($tab_column['actual_number']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);
                break;
        }
        $search_area[] = ['daterange:2', 'l.create_time', '日期'];


        //JS
        $js = '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
            <script type="text/javascript">
                $(function() {
                    //条形码
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{displayValue:false});
                    });
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "出库记录",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $sum_number = Db::name('wh_stock_log')
            ->alias('l')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->where($map)
            ->where($map2)
            ->sum('l.number');
        $total_str = "出库数量：{$sum_number}&nbsp;&nbsp;&nbsp;&nbsp;";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('出库记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            //->hideCheckbox()
            ->setPageTips($total_str,'info','topbtn')
            ->setExtraHtml($top_html,'block_top')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addTopButton('delete',['title' => '删除','href' => url('stockDelete',['type'=>'log']),'icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'stock_sn_img'  => 55,
                'type_name'     => 55,
                'type_name3'    => 55,
                'create_time'  => 110,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 盘存列表页
     */
    public function takeList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = input('stock_type',$this->_type_id);
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('takelist');

        $supplier_list = SupplierModel::getGroup(0,$type_pid);
        $type_list2 = StockTypeModel::getGroup($stock_type);
        $type_list3 = [];
        if(!empty($type_list2))$type_list3 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',$type_list2)]]);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        if($stock_type)$map[] = ['l.type_id','=',$stock_type];
        else $map[] = ['l.type_pid','=',$type_pid];
        $map[] = ['l.id','<>',""];
        // 数据列表
        $data_list = Db::name('wh_stock_take_log')
            ->alias('l')
            ->field('s.*,l.create_time,l.old_number,l.number as new_number,l.loss_number,u.nickname,t.title as type_name,ss.title as supplier_name')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=s.type_id')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->leftJoin('admin_user u','u.id=l.uid')
            ->where($map)
            ->where($map2)
            ->group('l.id')
            ->order('l.create_time desc')
            ->paginate()
            ->each(function ($v){

                //油漆类，显示三级分类
                if(in_array($v['type_pid'],ColorModel::$type_pid_arr) && !empty($v['type_id2'])){
                    $v['type_name'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value(['title']);
                }
                //四级分类
                $v['type_name3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value(['title']);

                return $v;
            })
        ;

        $stat = StockModel::getTakeStat($stock_type,'type_id');

        $top_arr = [
            [
                'left'  =>  ['title'=>'上期盘存','value'=>$stat['prev_new_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'盘前数量','value'=>$stat['old_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'盘后数量','value'=>$stat['new_number'],'angle'=>'kg']
            ],
        ];

        $top_html = StockModel::topStatHtml($top_arr);

        //列表表头
        $tab_column = [
            // 批量添加列
            'create_time'           =>  ['create_time', '日期','datetime'],
            'type_name'             =>  ['type_name', '物料类别'],
            'type_name3'            =>  ['type_name3', '类别'],
            'model'                 =>  ['model', '型号规格'],
            'supplier_name'         =>  ['supplier_name', '供应商'],
            'title'                 =>  ['title', '物料名称'],
            'supplier_color'        =>  ['supplier_color', '厂家色号'],
            'color_sn'              =>  ['color_sn', '自编号'],
            'old_number'            =>  ['old_number', '盘前数量'],
            'new_number'            =>  ['new_number', '盘后数量'],
            'loss_number'           =>  ['loss_number', '差异','callback',function($value, $data){

                $str = '<a class="text-primary">增加'.abs($value)."</a>";
                if($value<0)$str = '<a class="text-danger">减少'.abs($value)."</a>";
                return $str;
            },'__data__'],
            'nickname'              =>  ['nickname', '盘存人员'],
        ];
        //搜索头
        $search_area = [
            ['select:2', 's.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:2', 's.model', '型号规格', 'like'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['model']);
                if(empty($type_list3))unset($tab_column['type_name3']);
                $tab_column['title'] = ['title', '颜色名称'];
                unset($search_area[1]);
                $search_area[] = ['text:2', 's.supplier_color', '厂家色号', 'like'];
                $search_area[] = ['text:2', 's.color_sn', '自编号', 'like'];
                //无油温
                if(in_array($type_pid,ColorModel::$type_pid_not_heat_arr))unset($tab_column['heat']);
                break;
            //铝卷
            case 4:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);

                $search_area[] = ['text:2', 's.lot_sn', '色号', 'like'];
                break;
            //原材料
            case 3:
                //化工
            case 6:
            //其他
            default:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);
                break;
            //铝板
            case 5:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_name']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);

                $tab_column['old_number'] = ['old_number', '盘前数量(件)'];
                $tab_column['new_number'] = ['new_number', '盘后数量(件)'];
                $tab_column['loss_number'] = ['loss_number', '差异(件)'];
                break;
        }
        $search_area[] = ['daterange:2', 'l.create_time', '日期'];


        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "盘存记录",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('出库记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            //->hideCheckbox()
            ->setExtraHtml($top_html,'block_top')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'create_time'  => 110,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 采购单入库记录列表页
     */
    public function materialJoinList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = input('stock_type',$this->_type_id);
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('materialJoinList');

        $supplier_list = SupplierModel::getGroup(0,$type_pid);
        $type_list2 = StockTypeModel::getGroup($stock_type);
        $type_list3 = [];
        if(!empty($type_list2))$type_list3 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',$type_list2)]]);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        if($stock_type)$map[] = ['l.type_id','=',$stock_type];
        else $map[] = ['l.type_pid','=',$type_pid];
        $map[] = ['l.status','=',0];
        $map[] = ['l.cate','=',1];
        //$map[] = ['l.material_sn','<>',""];
        // 数据列表
        $data_list = Db::name('wh_stock_log')
            ->alias('l')
            ->field('l.*,s.title,s.color_sn,s.model as supplier_color,s.stock_sn as stock_sn_img,u.nickname,t.title as type_name,ss.title as supplier_name')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=s.type_id')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->leftJoin('admin_user u','u.id=l.uid')
            ->where($map)
            ->where($map2)
            ->group('l.id')
            ->order('l.create_time desc')
            ->paginate()
            ->each(function ($v){

                if(empty($v['material_sn']))$v['material_sn'] = $v['note'];

                //油漆类，显示三级分类
                if(in_array($v['type_pid'],ColorModel::$type_pid_arr) && !empty($v['type_id2'])){
                    $v['type_name'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value(['title']);
                }
                //四级分类
                $v['type_name3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value(['title']);

                return $v;
            })
        ;

        $stockStat = StockModel::getOneStat($stock_type,'type_id');

        $top_arr = [
            [
                'left'  =>  ['title'=>'总的库存数量','value'=>$stockStat['number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'入库数量','value'=>$stockStat['join_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'出库数量','value'=>$stockStat['out_number'],'angle'=>'kg']
            ],
        ];

        $top_html = StockModel::topStatHtml($top_arr);

        //列表表头
        $tab_column = [
            // 批量添加列
            'create_time'           =>  ['create_time', '日期','datetime'],
            'type_name'             =>  ['type_name', '物料类别'],
            'type_name3'            =>  ['type_name3', '类别'],
            'model'                 =>  ['model', '型号规格'],
            'supplier_name'         =>  ['supplier_name', '供应商'],
            'title'                 =>  ['title', '物料名称'],
            'supplier_color'        =>  ['supplier_color', '厂家色号'],
            'color_sn'              =>  ['color_sn', '自编号'],
            'number'                =>  ['number', '入库数量'],
            'num'                   =>  ['num', '入库数量'],
            'nickname'              =>  ['nickname', '库管'],
            'material_sn'           =>  ['material_sn', '采购单号'],
            ['stock_sn_img','条形码','callback',function($value, $data){
                $value = '<div class="js-gallery"> <img style="height: 35px;" class="image barcode" data-val="'.$value.'" data-original="" src=""></div>';
                return $value;
            },'__data__'],
            'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        //搜索头
        $search_area = [
            ['select:2', 's.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:2', 's.model', '型号规格', 'like'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['model']);
                unset($tab_column['num']);
                if(empty($type_list3))unset($tab_column['type_name3']);
                $tab_column['title'] = ['title', '颜色名称'];
                unset($search_area[1]);
                $search_area[] = ['text:2', 's.supplier_color', '厂家色号', 'like'];
                $search_area[] = ['text:2', 's.color_sn', '自编号', 'like'];
                //无油温
                if(in_array($type_pid,ColorModel::$type_pid_not_heat_arr))unset($tab_column['heat']);
                break;
            //铝卷
            case 4:
                unset($tab_column['type_name3']);
                unset($tab_column['num']);
                $tab_column['supplier_color'] = ['quality', '材质',ColorModel::getQuality()];
                $tab_column['color_sn'] = ['lot_sn', '色号'];

                $search_area[] = ['text:2', 's.lot_sn', '色号', 'like'];
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                unset($tab_column['type_name3']);
                unset($tab_column['num']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);
                break;
            //铝板
            case 5:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_name']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);

                $tab_column['note'] = ['note', '备注','text.edit'];
                $tab_column['color_sn'] = ['lot_sn', '批号'];
                $tab_column['num'] = ['num', '重量'];
                break;
        }
        $search_area[] = ['daterange:2', 'l.create_time', '日期'];


        //JS
        $js = '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
            <script type="text/javascript">
                $(function() {
                    //条形码
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{displayValue:true});
                    });
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "采购单入库记录",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('采购单入库记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_stock_log') // 设置表名
            //->hideCheckbox()
            ->setExtraHtml($top_html,'block_top')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addTopButton('archivesPrint',['title' => '批量打印','href' => url('codePrint'),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('print',['title' => '打印','href' => url('codePrint',['stock_sn' => '__stock_sn__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'stock_sn_img'  => 55,
                'type_name'     => 55,
                'type_name3'    => 55,
                'create_time'  => 110,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 退还列表页
     */
    public function refList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = input('stock_type',$this->_type_id);
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('refList');

        $supplier_list = SupplierModel::getGroup(0,$type_pid);
        $type_list2 = StockTypeModel::getGroup($stock_type);
        $type_list3 = [];
        if(!empty($type_list2))$type_list3 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',$type_list2)]]);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        if($stock_type)$map[] = ['l.type_id','=',$stock_type];
        else $map[] = ['l.type_pid','=',$type_pid];
        //$map[] = ['l.status','=',1];
        $map[] = ['l.cate','=',3];
        // 数据列表
        $data_list = Db::name('wh_stock_log')
            ->alias('l')
            ->field('l.*,s.title,s.color_sn,s.supplier_color,s.stock_sn as stock_sn_img,u.nickname,o.engineering,t.title as type_name,ss.title as supplier_name')
            ->leftJoin('mill_order o','o.id=l.order_id')
            ->leftJoin('wh_stock s','s.stock_sn=l.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=s.type_id')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->leftJoin('admin_user u','u.id=l.uid')
            ->where($map)
            ->where($map2)
            ->group('l.id')
            ->order('l.create_time desc')
            ->paginate()
            ->each(function ($v){

                if(!empty($v['note2']))$v['type_name'] = $v['note2'];
                if(empty($v['engineering']) && empty($v['archives_sn']))$v['engineering'] = $v['note'];
                elseif(empty($v['engineering']))$v['engineering'] = $v['archives_sn'];
                else $v['engineering'] .= "({$v['archives_sn']})";

                //油漆类，显示三级分类
                if(in_array($v['type_pid'],ColorModel::$type_pid_arr) && !empty($v['type_id2'])){
                    $v['type_name'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value(['title']);
                }
                //四级分类
                $v['type_name3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value(['title']);

                return $v;
            });

        $stockStat = StockModel::getOneStat($stock_type,'type_id');

        $top_arr = [
            [
                'left'  =>  ['title'=>'总的库存数量','value'=>$stockStat['number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'入库数量','value'=>$stockStat['join_number'],'angle'=>'kg']
            ],
            [
                'left'  =>  ['title'=>'出库数量','value'=>$stockStat['out_number'],'angle'=>'kg']
            ],
        ];

        $top_html = StockModel::topStatHtml($top_arr);

        //列表表头
        $tab_column = [
            // 批量添加列
            'type_name'             =>  ['type_name', '物料类别'],
            'type_name3'            =>  ['type_name3', '类别'],
            'model'                 =>  ['model', '型号规格'],
            'supplier_name'         =>  ['supplier_name', '供应商'],
            'title'                 =>  ['title', '物料名称'],
            'supplier_color'        =>  ['supplier_color', '厂家色号'],
            'color_sn'              =>  ['color_sn', '自编号'],
            'nickname'              =>  ['nickname', '库管'],
            'number'                =>  ['number', '退还数量'],
            'create_time'           =>  ['create_time', '日期','datetime'],
            'engineering'           =>  ['engineering', '使用工程'],
            //'right_button'          =>  ['right_button', '操作', 'btn']
        ];
        //搜索头
        $search_area = [
            ['select:2', 's.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:2', 's.model', '型号规格', 'like'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['model']);
                if(empty($type_list3))unset($tab_column['type_name3']);
                $tab_column['title'] = ['title', '颜色名称'];
                unset($search_area[1]);
                $search_area[] = ['text:2', 's.supplier_color', '厂家色号', 'like'];
                $search_area[] = ['text:2', 's.color_sn', '自编号', 'like'];
                //无油温
                if(in_array($type_pid,ColorModel::$type_pid_not_heat_arr))unset($tab_column['heat']);
                break;
            //铝卷
            case 4:
                unset($tab_column['type_name3']);
                $tab_column['supplier_color'] = ['quality', '材质',ColorModel::getQuality()];
                $tab_column['color_sn'] = ['lot_sn', '色号'];

                $search_area[] = ['text:2', 's.lot_sn', '色号', 'like'];
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);
                break;
            //铝板
            case 5:
                unset($tab_column['type_name3']);
                unset($tab_column['supplier_name']);
                unset($tab_column['supplier_color']);
                unset($tab_column['color_sn']);
                break;
        }
        $search_area[] = ['daterange:2', 'l.create_time', '日期'];


        //JS
        $js = '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
            <script type="text/javascript">
                $(function() {
                    //条形码
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{displayValue:false});
                    });
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "入库记录",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('退还记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            //->hideCheckbox()
            ->setExtraHtml($top_html,'block_top')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'stock_sn_img'  => 55,
                'type_name'     => 55,
                'type_name3'    => 55,
                'create_time'  => 110,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 添加入库记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function addJoin(){

        $stock_sn = input('stock_sn');

        if ($this->request->isPost() || input('ajax_form') == 'post'){
            //$data = $this->request->post();
            $data = input();

            $data['number'] = floatval($data['number']);

            if (empty($data['stock_sn'])) $this->error('请输入仓库编码');
            if(empty($data['number']) || $data['number'] < 0) $this->error('请输入入库重量');

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();
            $info['material_sn'] = input('material_sn');
            $info['note'] = input('note');

            if(!empty($data['num'])) {
                $data['num'] = floatval($data['num']);
                if($data['num'] < 0) $this->error('请输入入库数量');
            }

            if(empty($info)) $this->error('该产品不存在');
            //记录
            $re = StockModel::log(0,$info,$data,UID);
            if(!empty($re['msg']))$this->error($re['msg']);

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $type_pid = $this->_type_pid;
        $material_list = Db::name('wh_material')->where(['type_pid'=>$type_pid])->column('material_sn','material_sn');
        $archives_sn_list = Db::name('mill_order')->where(['status'=>1])->column('archives_sn','id');

        // 批量添加表单项
        $tab_column = [
            // 批量添加列
            'material_sn'             =>    ['select:6', 'material_sn','采购单号','',$material_list],
            'archives_sn'             =>    ['select:6', 'archives_sn','档案编号','',$archives_sn_list],
            'number'                  =>    ['number:12||||must', 'number', '入库数量'],
            'note'                    =>    ['textarea:12', 'note','备注'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                break;
            //铝卷
            case 4:
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                break;
            //铝板
            case 5:

                $tab_column['number'] = ['number:12||||must', 'number', '入库数量(件)'];
                break;
        }

        return ZBuilder::make('form')
            ->setPageTitle('添加入库记录') // 页面标题
            ->addHidden('stock_sn',$stock_sn)
            ->addHidden('type_pid',$type_pid)
            ->addFormItems($tab_column)
            //->setTrigger('type_pid','4,5','num',false)
            ->fetch();

    }

    /**
     * 添加出库记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function addOut(){

        $stock_sn = input('stock_sn');

        $type_pid = $this->_type_pid;
        $archives_sn_list = Db::name('mill_order')->where(['status'=>1])->column('archives_sn','id');

        if ($this->request->isPost()){
            $data = $this->request->post();

            $data['number'] = floatval($data['number']);

            if (empty($data['stock_sn'])) $this->error('请输入仓库编码');
            if(empty($data['number']) || $data['number'] < 0) $this->error('请输入出库数量');

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();
            $info['note'] = input('note');
            $info['order_id'] = input('order_id');
            if($info['order_id'])$info['archives_sn'] = $archives_sn_list[$info['order_id']];

            if(!empty($data['num'])) {
                $data['num'] = floatval($data['num']);
                if($data['num'] < 0) $this->error('请输入出库重量');
            }

            if(empty($info)) $this->error('该产品不存在');
            //记录
            $re = StockModel::log(1,$info,$data,UID);
            if(!empty($re['msg']))$this->error($re['msg']);

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        // 批量添加表单项
        $tab_column = [
            // 批量添加列
            'order_id'                =>    ['select:6', 'order_id','档案编号','',$archives_sn_list],
            'number'                  =>    ['number:12||||must', 'number', '出库数量'],
            'num'                     =>    ['number:12||||must', 'num', '出库数量'],
            'note'                    =>    ['textarea:12', 'note','备注'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($tab_column['num']);
                break;
            //铝卷
            case 4:
                unset($tab_column['num']);
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                unset($tab_column['num']);
                break;
            //铝板
            case 5:

                $tab_column['number'] = ['number:12||||must', 'number', '出库数量(件)'];
                $tab_column['num'] = ['number:12||||must', 'num', '出库重量(KG)'];
                break;
        }

        return ZBuilder::make('form')
            ->setPageTitle('添加出库记录') // 页面标题
            ->addHidden('stock_sn',$stock_sn)
            ->addHidden('type_pid',$type_pid)
            ->addFormItems($tab_column)
            ->setTrigger('type_pid','4,5','num',false)
            ->fetch();

    }

    /**
     * 添加盘存记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function addTake(){

        $stock_sn = input('stock_sn');

        if ($this->request->isPost()){
            $data = $this->request->post();

            $data['number'] = floatval($data['number']);

            if (empty($data['stock_sn'])) $this->error('请输入仓库编码');
            if(empty($data['number']) || $data['number'] < 0) $this->error('请输入正常的盘存重量');

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();

            if(!empty($data['num'])) {
                $data['num'] = floatval($data['num']);
                if($data['num'] < 0) $this->error('请输入盘存数量');
            }

            if(empty($info)) $this->error('该产品不存在');
            //记录
            $re = StockModel::takeLog(2,$info,$data,UID);
            if(!empty($re['msg']))$this->error($re['msg']);

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $type_pid = $this->_type_pid;

        // 批量添加表单项
        $tab_column = [
            // 批量添加列
            'number'                  =>    ['number:12||||must', 'number', '盘存数量'],
            'num'                     =>    ['number:12||||must', 'num', '盘存数量'],
        ];

        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                break;
            //铝卷
            case 4:
                break;
            //原材料
            case 3:
                //化工
            case 6:
                //其他
            default:
                break;
            //铝板
            case 5:

                $tab_column['number'] = ['number:12||||must', 'number', '盘存数量(件)'];
                $tab_column['num'] = ['number:12||||must', 'num', '盘存重量(KG)'];
                break;
        }

        return ZBuilder::make('form')
            ->setPageTitle('添加盘存记录') // 页面标题
            ->addHidden('stock_sn',$stock_sn)
            ->addFormItems($tab_column)
            //->setTrigger('type_pid','4,5','num',false)
            //->layout(['stock_sn'=>6,'number'=>6])
            ->fetch();

    }

    /**
     * 油漆覆盖率
     */
    public function paintCoList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $i =
        $row_area =
        $status3_area_sum =
        $number =
        $back_number =
        $actual_number =
        $row_area_rate =
        $coverage_rate = 0;

        $type_list2 = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',ColorModel::$type_pid_arr)]]);
        $type_list3 = [];
        if(!empty($type_list2)){
            foreach ($type_list2 as $tk=>$tv){
                $type_list3[$tk] = $tv;

                $type_where = [['t.pid','=',$tk]];
                $new_type_list = Db::name('wh_stock_type')
                    ->alias('t')
                    ->leftJoin('wh_stock_type tt','tt.id=t.pid')
                    ->where($type_where)
                    ->order('tt.sort asc,t.sort asc')
                    ->column("CONCAT(tt.title,'>',t.title)","t.id");
                $type_list3 = $type_list3+$new_type_list;
            }
        }

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if($mv[0] == 'l.type_id2'){
                $map2 .= " (l.type_id = {$mv[2]} or l.type_id2 = {$mv[2]}) ";
                unset($map[$mk]);
            }
        }
        $map = array_merge($map);
        // 数据列表
        $field = 'l.*,sum(l.number) as number,sum(l.back_number) as back_number,t.title as type_pname,s.model as supplier_color,s.title,s.heat,s.color_sn';
        $data_list = Db::name('wh_stock_use_log')
            ->alias('l')
            ->field($field)
            ->leftJoin('wh_stock s','s.id=l.stock_id')
            ->leftJoin('wh_stock_type t','t.id=s.type_pid')
            ->where($map)
            ->where($map2)
            ->group('l.archives_sn,l.stock_id')
            ->order('l.create_time desc,l.id desc')
            ->paginate();

        if(!empty($data_list)){
            foreach ($data_list as $k=>$v){
                $i++;
                if($v['order_id']){

                    //面积表颜色
                    $v['archives_color'] = Db::name('wh_order_color')->where([['order_id','=',$v['order_id']],['stock_sn','=',$v['stock_sn']]])->column('archives_color');
                    $v['archives_color'] = implode(',',$v['archives_color']);

                    //总面积
                    $v['row_area'] = Db::name('wh_order_color')->where([['order_id','=',$v['order_id']],['stock_sn','=',$v['stock_sn']]])->sum('row_area');
                    $v['row_area'] = round($v['row_area'],4);

                    //折弯日期
                    $give_where = [['g.order_id','=',$v['order_id']],['g.status','>=',3],['a.color','in',$v['archives_color']]];
                    $v['give_time'] = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($give_where)
                        ->order('g.status3_time asc')
                        ->value('g.status3_time');

                    //已折弯面积
                    $v['status3_area_sum'] = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($give_where)
                        ->sum('a.one_area');
                    $v['status3_area_sum'] = round($v['status3_area_sum'],4);

                }

                //折弯进度
                if($v['status3_area_sum']>=$v['row_area'])$v['archives_sn'] .= '<span class="label label-info">已喷完</span>';
                else $v['archives_sn'] .= '<span class="label label-danger">未喷完</span>';

                $v['heat'] = empty($v['heat'])?'':MaterialModel::$heat[$v['heat']];
                //实际用量=领用量-退还量
                $v['actual_number'] = $v['number'] - $v['back_number'];
                //平方率=实际使用量/总面积
                $v['row_area_rate'] = '';
                if(!empty($v['row_area']))$v['row_area_rate'] = (round(($v['actual_number']/$v['row_area']),4));
                //覆盖率=总面积/实际使用量
                $v['coverage_rate'] = '';
                if(!empty($v['actual_number']))$v['coverage_rate'] = (round(($v['row_area']/$v['actual_number']),4));

                $data_list[$k] = $v;

                $row_area += floatval($v['row_area']);
                $status3_area_sum += $v['status3_area_sum'];
                $number += $v['number'];
                $back_number += $v['back_number'];
                $actual_number += $v['actual_number'];
                $row_area_rate = (round(($actual_number/$row_area),4));
                $coverage_rate = 0;
                if($actual_number > 0)$coverage_rate = (round(($row_area/$actual_number),4));
            }

            $data_list[] = [
                'id'                    =>  '',
                'create_time'           =>  '',
                'give_time'             =>  '',
                'heat'                  =>  '合计',
                'row_area'              =>  $row_area,
                'status3_area_sum'      =>  $status3_area_sum,
                'number'                =>  $number,
                'back_number'           =>  $back_number,
                'actual_number'         =>  $actual_number,
                'row_area_rate'         =>  $row_area_rate,
                'coverage_rate'         =>  $coverage_rate,
            ];
        }

        $total_str = "总面积：{$row_area}&nbsp;&nbsp;&nbsp;&nbsp;已喷面积：{$status3_area_sum}&nbsp;&nbsp;&nbsp;&nbsp;领用量：{$number}&nbsp;&nbsp;&nbsp;&nbsp;退还量：{$back_number}&nbsp;&nbsp;&nbsp;&nbsp;实际用量：{$actual_number}&nbsp;&nbsp;&nbsp;&nbsp;平方率：{$row_area_rate}&nbsp;&nbsp;&nbsp;&nbsp;覆盖率：{$coverage_rate}";

        //CSS
        $css = "<style>
                .table-builder > tbody > tr > td {
                    border-bottom: 20px solid #edf6fd;
                }
                .dch-ul {
                    width: 100%;padding: 0;margin: 0;
                }
                .dch-li {
                    list-style-type: none;
                }
                .dch-bottom {
                    border-bottom: 1px solid #f0f0f0;
                }
            </style>";

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                        
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "油漆覆盖率",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            //->setPageTitle('油漆覆盖率（数量'.$data_list->total().'）') // 页面标题
            ->setPageTitle('油漆覆盖率') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            ->setPageTips($total_str,'info','topbtn')
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'l.type_id2', '折弯类型', 'eq','',$type_list3],
                ['text:2', 'l.engineering', '工程名称', 'like'],
                ['text:1', 'l.archives_sn', '档案号', 'like'],
                ['text:1', 's.supplier_color', '供应商色号', 'like'],
                ['daterange:2', 'l.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['create_time', '领用日期','date'],
                ['give_time', '折弯日期','date'],
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['type_pname', '折弯类型'],
                ['title', '颜色名称'],
                ['supplier_color', '供应商色号'],
                ['color_sn', '自编码'],
                ['heat', '油温'],
                ['row_area', '总面积'],
                ['status3_area_sum', '已喷面积'],
                ['number', '领用量'],
                ['back_number', '退还量'],
                ['actual_number', '实际用量'],
                ['row_area_rate', '平方率'],
                ['coverage_rate', '覆盖率'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->setExtraCss($css)
            ->addTopButton('addPaintCo',['title' => '添加覆盖率','href' => url('addPaintCo'),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['1600px', '70%'], 'title' => ['添加覆盖率', 'font-size:24px;text-align: center;']])
            ->addTopButton('ablequality',['title' => '导出当前数据','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('addPaintCo',['title' => '修改','href' => url('addPaintCo',['id'=>'__id__']),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['1600px', '70%'], 'title' => ['修改', 'font-size:24px;text-align: center;']])
            ->addRightButton('splitPaintCo',['title' => '插入工程','href' => url('splitPaintCo',['id' => '__id__']),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['900px', '70%'], 'title' => ['插入工程', 'font-size:24px;text-align: center;']])

            ->replaceRightButton(['order_id' => ['=',0]],'',['splitPaintCo'])
            ->replaceRightButton(['order_id' => ['>',0]],'',['addPaintCo'])
            ->replaceRightButton(['id' => ['=','']],'',['addPaintCo','splitPaintCo'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'heat'  => 60,
                'type_pname'  => 80,
                'status3_ok'  => 80,
                'engineering'  => 180,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 添加覆盖率
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function addPaintCo(){

        $id = input('param.id');
        // 获取数据
        $info = Db::name('wh_stock_use_log')->where(['id'=>$id])->find();

        //无物料编码(stock_sn)，order_id=0的就是后台手动录入覆盖率，同时也是领用退还记录
        if ($this->request->isPost()){
            $data = $this->request->post();

            $data['number'] = floatval($data['number']);

            //if (empty($data['stock_sn'])) $this->error('请输入仓库编码');
            if (empty($data['archives_sn'])) $this->error('请输入档案号');
            if (empty($data['stock_id'])) $this->error('请选择厂家色号');
            if(empty($data['number']) || $data['number'] < 0) $this->error('请输入领用数量');
            $data['create_time'] = strtotime($data['create_time']);
            $data['give_time'] = strtotime($data['give_time']);

            if($id)Db::name('wh_stock_use_log')->where(['id'=>$id])->update($data);
            else{
                $supplier_color = Db::name('wh_stock')->where(['id'=>$data['stock_id']])->find();
                $order_id = Db::name('mill_order')->where(['archives_sn'=>$data['archives_sn']])->value('id');

                $add = [
                    'use_sn'            =>  StockModel::useSn(),//领用编号
                    'uid'               =>  UID,
                    'order_id'          =>  intval($order_id),
                    'archives_sn'       =>  $data['archives_sn'],
                    //'stock_sn'          =>  $data['stock_sn'],
                    'number'            =>  $data['number'],
                    'back_number'       =>  $data['back_number'],
                    'create_time'       =>  $data['create_time'],
                    'give_time'         =>  $data['give_time'],

                    'stock_id'          =>  $supplier_color['id'],
                    'supplier_id'       =>  $supplier_color['supplier_id'],
                    'type_pid'          =>  $supplier_color['type_pid'],
                    'type_id'           =>  $supplier_color['type_id'],
                    'type_id2'          =>  $supplier_color['type_id2'],
                    'type_id3'          =>  $supplier_color['type_id3'],
                    'model'             =>  $supplier_color['model'],
                ];

                if(!empty($data['engineering']))$add['engineering'] = $data['engineering'];
                if(!empty($data['row_area']))$add['row_area'] = $data['row_area'];
                if(!empty($data['status3_area_sum']))$add['status3_area_sum'] = $data['status3_area_sum'];

                Db::name('wh_stock_use_log')->insert($add);
            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $color_where = [
            ['c.type_pid','in',ColorModel::$type_pid_arr]
        ];
        $color_list = Db::name('wh_stock')
            ->alias('c')
            ->leftJoin('wh_supplier s','s.id=c.supplier_id')
            ->leftJoin('wh_stock_type st','st.id=c.type_id')
            ->leftJoin('wh_stock_type stt','stt.id=c.type_pid')
            ->leftJoin('wh_supplier_color_type ct','ct.id=c.color_type_id')
            ->where($color_where)
            ->column("CONCAT(c.title,' | ',c.model,'  | ',s.title_abb,'   | ',stt.title,'    | ',st.title,'     | ',ct.title,'      | ',color_sn)",'c.id');
        //echo Db::name('mill_order')->getLastSql();exit;

        return ZBuilder::make('form')
            ->setPageTitle('添加覆盖率记录') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['text:6||||must', 'archives_sn','档案编号'],
                ['text:6||||must', 'engineering', '工程名称'],
                ['text:6||||must', 'status3_area_sum', '已喷面积'],
                ['text:6||||must', 'row_area', '总面积'],
                ['date:6||||must', 'give_time', '折弯时间','',date('Y-m-d')],
                ['date:6||||must', 'create_time', '领用时间','',date('Y-m-d')],
                ['select:12||||must', 'stock_id','厂家色号','',$color_list],
                ['number:6||||must', 'number', '领用数量'],
                ['number:6||||must', 'back_number', '退还数量'],
            ])
            ->setFormData($info)
            ->fetch();

    }

    /**
     * 插入工程覆盖率
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function splitPaintCo(){

        $id = input('id');

        if ($this->request->isPost()){
            $data = $this->request->post();

            if (empty($data['order_ids'])) $this->error('请选择档案号');
           $order_ids = $data['order_ids'];

            $where = ['id'=>$data['id']];
            $info = Db::name('wh_stock_use_log')->where($where)->find();
            if(empty($info)) $this->error('该记录不存在');

            //总面积
            $info['row_area'] = Db::name('wh_order_color')->where([['id','=',$info['order_color_id']]])->sum('row_area');
            $row_area = $info['row_area'] = round($info['row_area'],4);

            $order_list = [];
            foreach ($order_ids as $order_id){

                $order = Db::name('mill_order')
                    ->alias('o')
                    ->field('o.*,c.id as order_color_id,sum(c.row_area) as row_area')
                    ->leftJoin('wh_order_color c',"c.order_id=o.id and c.stock_sn='{$info['stock_sn']}'")
                    ->where(['o.id'=>$order_id])
                    ->find();
                if(empty($order['order_color_id']))$this->error("[{$order['archives_sn']}]档案号无此色号，或未定色");

                //总面积
                $row_area += $order['row_area'];
                $order_list[] = $order;
            }

            //根据面积分配领用量，退还量
            $number = $info['number'];
            $back_number = $info['back_number'];

            foreach ($order_list as $v){

                //面积比例
                $area_scale = round(($v['row_area']/$row_area),4);
                //分配到的数量
                $area_number = round(($info['number']*$area_scale),2);
                $area_back_number = round(($info['back_number']*$area_scale),2);
                //总数量-分配到的数量
                $number -= $area_number;
                $back_number -= $area_back_number;

                $add = [
                    'uid'               =>  UID,
                    'order_id'          =>  $v['id'],
                    'number'            =>  $area_number,
                    'back_number'       =>  $area_back_number,
                    'archives_sn'       =>  $v['archives_sn'],
                    'engineering'       =>  $v['engineering'],
                    'order_color_id'    =>  $v['order_color_id'],
                    'row_area'          =>  $v['row_area'],
                    //'status3_area_sum'  =>  $v['status3_area_sum'],
                    //'give_time'         =>  $v['give_time'],

                    'use_sn'            =>  $info['use_sn'],//领用编号
                    'stock_sn'          =>  $info['stock_sn'],
                    'stock_id'          =>  $info['stock_id'],
                    'log_id'            =>  $info['log_id'],
                    'log_id_back'       =>  $info['log_id_back'],
                    'supplier_id'       =>  $info['supplier_id'],
                    'type_pid'          =>  $info['type_pid'],
                    'type_id'           =>  $info['type_id'],
                    'model'             =>  $info['model'],
                    'create_time'       =>  $info['create_time'],
                ];

                Db::name('wh_stock_use_log')->insert($add);
            }


            //更新主记录的数量
            Db::name('wh_stock_use_log')->where(['id'=>$data['id']])->update(['number'=>$number,'back_number'=>$back_number]);

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $info = Db::name('wh_stock_use_log')->where(['id'=>$id])->find();

        //$order_field = "CONCAT(archives_sn,'  | ',batch,' | ',engineering)";
        $order_field = "archives_sn";
        $order_where = ['stock_sn'=>$info['stock_sn']];
        $order_list = Db::name('wh_order_color')->where($order_where)->column($order_field,'order_id');
        return ZBuilder::make('form')
            ->setPageTitle('添加覆盖率记录') // 页面标题
            ->addHidden('id',$id)
            ->addFormItems([ // 批量添加表单项
                ['select:12||||must', 'order_ids','档案编号','',$order_list,'','multiple'],
            ])
            ->fetch();

    }

    //根据厂家色号查找对应供应商
    public function supplierColorList(){
        $action = new Color();

        return $action->supplierColorList();
    }

    //物料条形码
    public function codePrint(){

        $pram = input();
        $pram['print'] = input('print',1);

        $data = StockModel::codePrint($pram);

        if(!empty($data['msg']))$this->error($data['msg']);

        exit($data['html']);

    }

    //AJAX类别列表
    public function getStockType(){

        $action = new Color();

        return $action->getStockType();
    }

    //库存批量删除
    public function stockDelete(){
        $ids = input('ids');
        $type = input('type');

        if($type == 'log'){
            //删除出入库记录
            if(is_array($ids))$ids = implode(',',$ids);
            if(empty($ids))$this->error('请选择记录');
            Db::name('wh_stock_log')->where([['id','in',$ids]])->delete();
        }
        else{
            foreach ($ids as $id){
                $info = Db::name('wh_stock')
                    ->alias('s')
                    ->field('s.*,t.title as type_name,tt.title as type_pname')
                    ->leftJoin('wh_stock_type t','t.id=s.type_id')
                    ->leftJoin('wh_stock_type tt','tt.id=s.type_pid')
                    ->where(['s.id'=>$id])
                    ->find();

                if(!empty($info)){
                    Db::name('wh_stock')->where(['id'=>$id])->delete();
                    Db::name('wh_stock_log')->where(['stock_sn'=>$info['stock_sn']])->delete();
                    Db::name('wh_stock_take_log')->where(['stock_sn'=>$info['stock_sn']])->delete();
                    // 记录行为
                    $sql_key = "";
                    $sql_val = "";
                    foreach ($info as $k=>$v){
                        $sql_key .= "`{$k}`,";
                        $sql_val .= "'{$v}',";
                    }
                    $sql = "\r\n物料类型：{$info['type_pname']}-->{$info['type_name']}  库存名称：{$info['title']}  库存编号：【{$info['stock_sn']}】\r\nINSERT INTO `xxy`.`xxy_wh_stock` (".trim($sql_key,',').") VALUES (".trim($sql_val,',').")";

                    action_log('stock_delete', 'wh_stock', $id, UID, $sql);
                }
            }

        }

        $this->success('删除成功');
    }

    //库存批量修改
    public function editMoreStock(){

        $ids = input('ids');
        if(is_array($ids))$ids = implode(',',$ids);
        if(empty($ids))$this->error('请选择库存');

        if ($this->request->isPost()){
            $data = $this->request->post();

            if (empty($data['ids'])) $this->error('请选择库存');

            $ids = explode(',',$data['ids']);

            foreach ($ids as $id){

                $info = Db::name('wh_stock')->where(['id'=>$id])->find();
                Db::name('wh_stock')->where(['id'=>$id])->update(['note'=>$data['note']]);

            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $supplier_color = Db::name('wh_stock')->where([['id','in',$ids]])->column('model');

        $supplier_color = implode(',',$supplier_color);

        return ZBuilder::make('form')
            ->setPageTitle('批量修改') // 页面标题
            ->addHidden('ids',$ids)
            ->addFormItems([ // 批量添加表单项
                ['static:12', 'supplier_color','规格','',$supplier_color],
                ['text:12||||must', 'note', '备注'],
            ])
            ->fetch();

    }
}
